<?php
/**
 * @author Alecsandru Gabriel DINU
 * @since Jun 12, 2008
 */
if (!class_exists('AlfaConfiguration')) {
	
	require_once("exception/ConfigurationException.php");
	require_once("utils/FileUtilities.php");
	require_once("Singleton_Interface.php");
	
	/**
	 * Simple configuration class based on the singleton design pattern
	 * which load configuration values from an ini file in the class path
	 */
	class AlfaConfiguration implements Singleton_Interface {
		
	    private static $theInstance;
	    private $xml; // SimpleXML
	    const configFile = "env/config.xml";
	    
	    private function __construct() {
	        $this->load();
	    }
	
	    public static function getInstance() {
	        if (!self::$theInstance) {
	            self::$theInstance = new AlfaConfiguration();
	        }
	        return self::$theInstance;
	    }
	
	    private function load() {
			$xmlStr = FileUtilities::getFileContent(self::configFile);
        	$this->xml = new SimpleXMLElement($xmlStr);
			
	    }
	
	    public function getString($name, $defaultVal=null) {
	        $xpath = "/config/$name";
	        $result = $this->xml->xpath($xpath);
	        if (sizeof($result) > 0) {
	            return (string)$result[0];
	        }
	        if (!isset($defaultVal)) {
	            throw new ConfigurationException("Missing configuration value '$name' in " . self::configFile);
	        }
	        return $defaultVal;
	    }

	    public function item($name, $defaultVal=null) {
	    	return $this->getString($name, $defaultVal);
	    }
	    
	    public function getInt($name, $defaultVal=null) {
	        return $this->getString($name, $defaultVal);
	    }
	
	    public function getBoolean($name, $defaultVal=null) {
	        $val = strtolower($this->getString($name, $defaultVal));
	        if ($val == "true" || $val == "yes" || $val == "1" || $val == "on") {
	            return true;
	        }
	        return false;
	    }
	
	    public function get($name) {
	        $xpath = "/config/$name";
	        $result = $this->xml->xpath($xpath);
	        return $result;
	    }
		
	    /**
	     * Forces the config file to be read again
	     */
		public function reload() {
			unset($this->xml);
			$this->load();
		}
	    
	    
		/**
	     * Override clone method to throw exception
	     * @access public
	     * @return void
	     * @throws Exception
	     */
	    public function __clone() {
	    	throw new Exception('You cannot clone singleton object');
	    }

	    
	}
}